package com.example.framelib.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.example.framelib.utils.ActivityManagerUtil;
import com.example.framelib.utils.EventCenter;
import com.example.framelib.utils.Log;
import com.zhy.autolayout.AutoLayoutActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

public abstract class BaseActivity extends AutoLayoutActivity {
    private long startTime;
    private boolean isFirstResume;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        startTime = System.currentTimeMillis();
        ActivityManagerUtil.create().addActivity(this);

        super.onCreate(savedInstanceState);
        if (getContentView() > 0) {
            setContentView(getContentView());
        }

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        isFirstResume = true;
    }

    public abstract void initView();

    public abstract void initData();

    @Override
    protected void onResume() {
        super.onResume();
        if (startTime != 0) {
            Log.trace(getClass().getSimpleName(), "界面启动耗时" + (System.currentTimeMillis() - startTime) + "毫秒");
            startTime = 0;
        }
        if (isFirstResume) {
            if (isApplyButterKnife()) {
                Log.e("Tag" , "11111111111111111111111111");
                ButterKnife.bind(this);
            }
            if (isApplyEventBus()) {
                EventBus.getDefault().register(this);
            }
            initView();
            initData();
            isFirstResume = false;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        fixInputMethodManagerLeak(this);
        ActivityManagerUtil.create().finishActivity(this);
        if (isApplyEventBus()) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCenter eventCenter) {
        if (eventCenter != null) {
            onEventCome(eventCenter);
        }
    }

    public abstract int getContentView();

    public abstract boolean isApplyEventBus();

    public abstract boolean isApplyButterKnife();

    public abstract void onEventCome(EventCenter eventCenter);


    public void startActivity(Class cls) {
        Intent mIntent = new Intent(this, cls);
        startActivity(mIntent);
    }

    /**
     * 检查是否有某项权限
     * @param permission
     * @return
     */
    public boolean checkPermission(String permission){
        if (ContextCompat.checkSelfPermission(this,permission)
                != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
        return true;
    }

    public boolean checkPermissions(String[] permissions){
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this,permission)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }

        return true;
    }

    /**
     * 检查是缺少的权限
     * @param permissions
     * @return
     */
    public String[] checkLackPermissions(String[] permissions){
        List<String> lackPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (!checkPermission(permission)) {
                lackPermissions.add(permission);
            }
        }
        String[] lackPermissionArray=null;
        if (lackPermissions.size()>0) {
            lackPermissionArray = new String[lackPermissions.size()];
            lackPermissions.toArray(lackPermissionArray);
        }

        return  lackPermissionArray;
    }

    public void requestSystemPermissions(String[] permissions,int requestCode){
        ActivityCompat.requestPermissions(this,
                permissions,requestCode);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        if (mRequestPermission != null){
            mRequestPermission.onRequestResult(requestCode,permissions,grantResults);
        }
        super.onRequestPermissionsResult(requestCode,permissions,grantResults);
    }

    private RequestPermission mRequestPermission;
    public void setRequestPermissionListener(RequestPermission requestPermission){
        mRequestPermission = requestPermission;
    }


    public interface RequestPermission {
        void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults);
    }

    /****
     * @param destContext
     * 某个界面上出现InputMethodManager持有一Activity,
     * 导致该Activity无法回收.如果该Activity再次被打开,则旧的会释放掉,但新打开的会被继续持有无法释放回收
     */
    public static void fixInputMethodManagerLeak(Context destContext) {
        if (destContext == null) {
            return;
        }

        InputMethodManager imm = (InputMethodManager) destContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm == null) {
            return;
        }

        String[] arr = new String[]{"mCurRootView", "mServedView", "mNextServedView"};
        Field f = null;
        Object obj_get = null;
        for (int i = 0; i < arr.length; i++) {
            String param = arr[i];
            try {
                f = imm.getClass().getDeclaredField(param);
                if (f.isAccessible() == false) {
                    f.setAccessible(true);
                } // author: sodino mail:sodino@qq.com
                obj_get = f.get(imm);
                if (obj_get != null && obj_get instanceof View) {
                    View v_get = (View) obj_get;
                    if (v_get.getContext() == destContext) { // 被InputMethodManager持有引用的context是想要目标销毁的
                        f.set(imm, null); // 置空，破坏掉path to gc节点
                    } else {
                        // 不是想要目标销毁的，即为又进了另一层界面了，不要处理，避免影响原逻辑,也就不用继续for循环了
                       /* if (QLog.isColorLevel()) {
                            QLog.d(ReflecterHelper.class.getSimpleName(), QLog.CLR, "fixInputMethodManagerLeak break, context is not suitable, get_context=" + v_get.getContext()+" dest_context=" + destContext);
                        }*/
                        break;
                    }
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }


}
